#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include<omp.h>
#include<ctype.h>

#define NUM_THREAD 2


int ispalindromo(char *string);
int tamArquivo(FILE *f);
int contPalindromo(char *f, int tamIni, int tamMax);
int crivo (int n);


int main(){

	int cont = 0;
	int tam;
	double time;
	clock_t start; 
	clock_t end;


	FILE *arq;
	arq = fopen("wikipedia.txt","r");
	if(arq == NULL)
		printf("Falha ao abrir o arquivo");
	else{	
		
		char *text;
		int id;

		tam = tamArquivo(arq);
		text = malloc(tam*sizeof(char));
		
		fread(text, 1, tam, arq);
		
		omp_set_num_threads(2);

		start = clock();
		/*reduction (+:cont) faz com que cada thread 
		possua um cont e depois soma tudo no final.*/
		
		printf("tam = %d    tam/2 = %d \n", tam, tam/2);
		#pragma omp parallel reduction(+:cont) private(id)
		#pragma omp sections
		{
			#pragma omp section
			{	
				cont += contPalindromo(text,0,tam/2);
				id = omp_get_thread_num();
				printf("thread %d   cont %d\n", id, cont);

			}
			#pragma omp section
			{
				cont += contPalindromo(text,tam/2,tam);
				id = omp_get_thread_num();
				printf("thread %d   cont %d\n", id, cont);


			}
		}
 
		/*cont = contPalindromo(text,0,tam);*/

		end = clock();			

	}

	printf("%d\n",cont);
	time = ((double)(end-start)/(double)CLOCKS_PER_SEC);
	printf("tempo é %lf\n", time);
	
	return 0;
}

int ispalindromo(char *string){

	
	int i=0;
	int tam = strlen(string);
	
	if( tam%2 == 0 ){

		for(i = 0 ; i < tam/2 ; i++){

			if(string[i] != string[tam-1-i])
				return 0;

		}
	return 1;
	}
	else{
		while( i != tam/2){
			if(string[i] != string[tam-1-i])
				return 0;
			i++;
		}
	
	return 1;
	}
}

int tamArquivo(FILE *f){
	
	int size = 0;
	fseek(f,0,SEEK_END);
	size = ftell(f);
	fseek(f,0,SEEK_SET);
	return size;

}

int contPalindromo(char *text, int tamIni, int tamMax){
	
	char *word;
	char caracter; 
	int stop = 0;
	int cont; 
	int percorreText = tamIni+1;
	int i = 0;
	/*int id*/;

	
	word = malloc(10*sizeof(char));

	caracter = text[tamIni];

	while(!stop){
		
		if(percorreText == tamMax){
			stop = 1;
		}else{

			if(isalnum(text[percorreText])){
				word[i] = text[percorreText];
				i++;
			}
			else{
				word[i] = '\0';
				
				if(ispalindromo(word) && i > 2){
					cont++;
					/*printf("%s\n",word);*/
				}
				i = 0;
			}

		}
		percorreText++;
	}
	return cont;
}



	/*int i;*/


	/*if(tamIni > 0){
		for( i=tamIni ; i > 0 ; i--){
			
			if()
			aux = fgetc(f);

		}
		tamIni = i+1;*/
	
